package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class ArticleFragment extends Fragment{
    Article article;
    ImageView articleImage;
    ImageView articleAuthorImage;
    TextView articleAuthorName;
    TextView articleCreateTime;
    TextView articleTitle;
    TextView articleContent;
    User author;
    Button StartButton;
    Button CollectButton;
    Button articleVoicePlayButton;

    String getImageUrl=SeverURL.URL+"/get_image/";
    String getUserImageUrl=SeverURL.URL+"/get_profile_photo/";
    String getVoiceUrl = SeverURL.URL + "/get_audio/";
    String likeURL = SeverURL.URL + "/like_article";
    String startURL = SeverURL.URL + "/start_article";
    public ArticleFragment() {
        // Required empty public constructor
    }


    public void setArticle(Article article) {
        this.article = article;
        this.author = article.getAuthor();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page, container, false);
        if (article == null) {
            return view; // 提前返回，避免空指针
        }

        initViews(view);
        initData();

        return view;
    }

    private void initViews(View view) {
        articleImage = view.findViewById(R.id.image_carousel);
        articleAuthorImage = view.findViewById(R.id.author_avatar);
        articleAuthorName = view.findViewById(R.id.author_name);
        articleCreateTime = view.findViewById(R.id.publish_time);
        articleTitle = view.findViewById(R.id.article_title);
        articleContent = view.findViewById(R.id.article_content);
        StartButton = view.findViewById(R.id.like_button);
        CollectButton = view.findViewById(R.id.collect_button);
        articleVoicePlayButton = view.findViewById(R.id.articleVoicePlayButton);
    }
    public void reclick(Article article) {
        this.article = article;
        this.author = article.getAuthor();
        initData();
    }
    private void initData() {
        articleAuthorName.setText(author.getUsername());
        articleCreateTime.setText(article.getCreateTime());
        articleTitle.setText(article.getTitle());
        articleContent.setText(article.getContent());
        //使用Glide加载图片
        Glide.with(this)
                .load(getImageUrl + article.getImageUrl())
                .into(articleImage);
        Glide.with(this)
                .load(getUserImageUrl + author.getProfilePictureUrl())
                .into(articleAuthorImage);
        if (article.getAudioUrl() == null || article.getAudioUrl().isEmpty()) {
            articleVoicePlayButton.setVisibility(View.GONE);
            return;
        }

        StartButton.setText("👍 "+article.getThumbsUpCount());
        CollectButton.setText("⭐ "+article.getCollectCount());
        articleVoicePlayButton.setOnClickListener(v -> {
            if (article.getAudioUrl() == null || article.getAudioUrl().isEmpty()) {
                articleVoicePlayButton.setText("没有音频");
                return;
            }
                if (articleVoicePlayButton.getText().equals("播放中...")) {
                    Toast.makeText(getContext(), "音频正在播放", Toast.LENGTH_SHORT).show();
                    return; // 如果正在播放，则不执行
                }
                // 播放音频的逻辑
                try {
                    // 初始化MediaPlayer
                    android.media.MediaPlayer mediaPlayer = new android.media.MediaPlayer();

                    // 设置音频源
                    mediaPlayer.setDataSource(getVoiceUrl + article.getAudioUrl());

                    // 准备播放
                    mediaPlayer.prepare();

                    // 开始播放
                    mediaPlayer.start();

                    // 设置播放完成监听器
                    mediaPlayer.setOnCompletionListener(mp -> {
                        mp.release(); // 播放完成后释放资源
                        articleVoicePlayButton.setText("播放音频"); // 恢复按钮文字
                    });

                    articleVoicePlayButton.setText("播放中..."); // 更新按钮文字


                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "播放失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
        });
        StartButton.setOnClickListener(v -> {
            SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
            //如果没有获取到用户名和密码，则提示用户登录
            if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                builder.setTitle("提示")
                        .setMessage("请先登录")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 关闭对话框
                            dialog.dismiss();
                        })
                        .show();
                return ;
            }
            String username = sharedPref.getString("username", null);
            String password = sharedPref.getString("password", null);
            String articleId = String.valueOf(article.getId());
            // 创建 OkHttpClient 实例
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            // 创建请求体
            JSONObject json = new JSONObject();
            try {
                json.put("username", username);
                json.put("password", password);
                json.put("articleID", articleId);
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            RequestBody requestBody = RequestBody.create(
                    json.toString(),
                    MediaType.parse("application/json; charset=utf-8")
            );

            // 创建请求
            Request request = new Request.Builder()
                    .url(likeURL)  // 替换为实际服务器地址
                    .post(requestBody)
                    .build();
            // 异步发送请求
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                    if (response.isSuccessful()) {
                        requireActivity().runOnUiThread(() -> {
                            StartButton.setText("👍 "+(article.getThumbsUpCount()+1));
                            article.setThumbsUpCount(article.getThumbsUpCount()+1);
                            Toast.makeText(requireContext(), "点赞成功", Toast.LENGTH_SHORT).show();
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), "点赞失败: " + response.message(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            });
        });
        CollectButton.setOnClickListener(v ->{
            SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
            //如果没有获取到用户名和密码，则提示用户登录
            if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                builder.setTitle("提示")
                        .setMessage("请先登录")
                        .setPositiveButton("确定", (dialog, which) -> {
                            // 关闭对话框
                            dialog.dismiss();
                        })
                        .show();
                return ;
            }
            String username = sharedPref.getString("username", null);
            String password = sharedPref.getString("password", null);
            String articleId = String.valueOf(article.getId());
            // 创建 OkHttpClient 实例
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            // 创建请求体
            JSONObject json = new JSONObject();
            try {
                json.put("username", username);
                json.put("password", password);
                json.put("articleID", articleId);
            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

            RequestBody requestBody = RequestBody.create(
                    json.toString(),
                    MediaType.parse("application/json; charset=utf-8")
            );

            // 创建请求
            Request request = new Request.Builder()
                    .url(startURL)  // 替换为实际服务器地址
                    .post(requestBody)
                    .build();
            // 异步发送请求
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                    if (response.isSuccessful()) {
                        requireActivity().runOnUiThread(() -> {
                            CollectButton.setText("⭐ "+(article.getCollectCount()+1));
                             article.setThumbsUpCount(article.getCollectCount()+1);
                            Toast.makeText(requireContext(), "收藏成功", Toast.LENGTH_SHORT).show();
                        });
                    } else {
                        requireActivity().runOnUiThread(() -> {
                            Toast.makeText(requireContext(), "收藏失败: " + response.message(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
            });
        });




    }
}



